﻿using System;
using YaAppoint.RoslynCompiler;

namespace YaAppoint.OnlineServiceCache
{
    public abstract class OnlineService
    {
        // 文本模板ID
        public Guid TemplateId { get; set; }

        // 服务类型
        public TextTemplates.OnlineServiceType Type { get; set; }

        // 服务名称
        public string Name { get; set; }

        // code的MD5值
        public string MD5 { get; set; }

        // 动态编译程序集加载上下文（用于卸载程序集）
        public DynamicAssemblyLoadContext AssemblyLoadContext { get; set; }

        // 获取动态编译的实例
        public abstract object GetInstance();

        // 设置动态设置的实例
        public abstract void SetInstance(object instance);
    }

    public class OnlineService<T>: OnlineService
    {
        // 实例
        public T Instance { get; set; }

        // 读取实例
        public override object GetInstance()
        {
            return Instance;
        }

        // 设置实例
        public override void SetInstance(object instance)
        {
            if (instance is T typedInstance)
            {
                Instance = typedInstance;
            }
            else
            {
                throw new ArgumentException($"Instance must be of type {typeof(T).Name}");
            }
        }
    }
}
